﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SecurityDev
{
    public partial class InitializePerson : Form
    {
        decimal person_seq;

        public InitializePerson()//add person
        {
            InitializeComponent();

            this.Text = "Add object";
            addChangeCustomer.Text = "Add customer";
            addChangeCustomer.Click += new System.EventHandler(AddCustomer_Click);

            var objectsStr = from o in DS.outpost._object
                             select string.Format("Id: {0}; Name: {1}", o.obj_seq.ToString(), o.obj_name);

            foreach (var item in objectsStr)
            {
                objectsCheckedListBox.Items.Add((object)item);
            }
        }

        public InitializePerson(decimal per_seq)//change person
        {
            InitializeComponent();

            this.Text = "Change person id: " + per_seq;
            addChangeCustomer.Text = "Change customer";
            addChangeCustomer.Click += new System.EventHandler(ChangeCustomer_Click);
            person_seq = per_seq;

            OutpostDS.personRow newPersonR = DS.outpost.person.FindByperson_seq(person_seq);

            nameTextBox.Text = newPersonR.person_name;
            lastNameTextBox.Text = newPersonR.person_lastname;
            phoneTextBox.Text = newPersonR.person_phone;
            emailTextBox.Text = newPersonR.person_email;
            addressTextBox.Text = newPersonR.person_adress;
            isCustcheckCheckBox.Checked = Convert.ToBoolean(newPersonR.person_is_customer);
            photoTextBox.Text = newPersonR.person_photo;

            var objectsStr = from o in DS.outpost._object
                             select string.Format("Id: {0}; Name: {1}", o.obj_seq.ToString(), o.obj_name);

            decimal[] objSeqsIn_ObjPer = (from op in DS.outpost.object_person
                                          where op.person_seq == person_seq
                                          select op.obj_seq).ToArray();

            foreach (var objectR in DS.outpost._object)
            {
                if (CheckObjectSeqInObjPer(objectR, objSeqsIn_ObjPer))
                {
                    objectsCheckedListBox.Items.Add((object)string.Format("Id: {0}; Name: {1}", objectR.obj_seq.ToString(), objectR.obj_name), true);
                }
                else
                {
                    objectsCheckedListBox.Items.Add((object)string.Format("Id: {0}; Name: {1}", objectR.obj_seq.ToString(), objectR.obj_name));
                }
            }
        }

        bool CheckObjectSeqInObjPer(OutpostDS.objectRow objR, decimal[] obj_seqs)
        {
            foreach (var pers_seq in obj_seqs)
            {
                if (pers_seq == objR.obj_seq)
                {
                    return true;
                }
            }
            return false;
        }

        private void ChoosePhoto_Btn_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Image Files |*.jpg;*.jpeg;*.bmp;*.png|All Files (*.*)|*.*";;
            openFileDialog1.FilterIndex = 1;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                photoTextBox.Text = openFileDialog1.FileName;
            }
        }

        private void AddCustomer_Click(object sender, EventArgs e)
        {
            if (!CheckText.IsValidPhone(phoneTextBox.Text))
            {
                invalidPhoneLabel.Visible = true;
                //MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (!CheckText.IsValidEmail(emailTextBox.Text))
            {
                invalidEmailLabel.Visible = true;
                //MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (nameTextBox.Text == "" || lastNameTextBox.Text == "" ||
                addressTextBox.Text == "" || photoTextBox.Text == "")
            {
                if (MessageBox.Show("Some fields aren't filled. Do you want to continue?",
                    "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==
                    System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            var last_person_seq = (from p in DS.outpost.person
                                   orderby p.person_seq ascending
                                   select p.person_seq).LastOrDefault();

            OutpostDS.personRow newPersonR = DS.outpost.person.NewpersonRow();

            newPersonR.person_seq = ++last_person_seq;
            newPersonR.person_name = nameTextBox.Text;
            newPersonR.person_lastname = lastNameTextBox.Text;
            newPersonR.person_phone = phoneTextBox.Text;
            newPersonR.person_email = emailTextBox.Text;
            newPersonR.person_adress = addressTextBox.Text;
            newPersonR.person_is_customer = isCustcheckCheckBox.Checked ? 1U : 0U;
            newPersonR.person_photo = photoTextBox.Text;


            DS.outpost.person.AddpersonRow(newPersonR);

            decimal op_seq = (from op in DS.outpost.object_person
                              orderby op.seq ascending
                              select op.seq).LastOrDefault();


            decimal obj_seq;
            for (int i = 0; i < objectsCheckedListBox.CheckedItems.Count; i++)
            {
                obj_seq = Convert.ToDecimal(((string)objectsCheckedListBox.CheckedItems[i]).Substring(4, ((string)objectsCheckedListBox.CheckedItems[i]).IndexOf(';') - 4));
                DS.outpost.object_person.Addobject_personRow(++op_seq, DS.outpost.person.FindByperson_seq(newPersonR.person_seq), DS.outpost._object.FindByobj_seq(obj_seq));
            }

            try
            {
                DS.personAdapter.Update(DS.outpost.person);
                DS.object_personAdapter.Update(DS.outpost.object_person);

            }
            catch (Exception xException)
            {
                MessageBox.Show(xException.Message);
            }
            Close();
        }

        private void ChangeCustomer_Click(object sender, EventArgs e)
        {
            if (!CheckText.IsValidPhone(phoneTextBox.Text))
            {
                invalidPhoneLabel.Visible = true;
                //MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            invalidPhoneLabel.Visible = false;

            if (!CheckText.IsValidEmail(emailTextBox.Text))
            {
                invalidEmailLabel.Visible = true;
                //MessageBox.Show("Phone isn't Valid", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            invalidEmailLabel.Visible = false;

            if (nameTextBox.Text == "" || lastNameTextBox.Text == "" ||
                addressTextBox.Text == "" || photoTextBox.Text == "")
            {
                if (MessageBox.Show("Some fields aren't filled. Do you want to continue?",
                    "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) ==
                    System.Windows.Forms.DialogResult.No)
                {
                    return;
                }
            }

            OutpostDS.personRow changePersonR = DS.outpost.person.FindByperson_seq(person_seq);

            changePersonR.person_name = nameTextBox.Text;
            changePersonR.person_lastname = lastNameTextBox.Text;
            changePersonR.person_phone = phoneTextBox.Text;
            changePersonR.person_email = emailTextBox.Text;
            changePersonR.person_adress = addressTextBox.Text;
            changePersonR.person_is_customer = isCustcheckCheckBox.Checked ? 1U : 0U;
            changePersonR.person_photo = photoTextBox.Text;
            
            decimal op_seq = (from op in DS.outpost.object_person
                              orderby op.seq ascending
                              select op.seq).LastOrDefault();


            decimal obj_seq;
            OutpostDS.object_personRow opR;
            for (int i = 0; i < objectsCheckedListBox.Items.Count; i++)
            {
                obj_seq = Convert.ToDecimal(((string)objectsCheckedListBox.Items[i]).Substring(4, ((string)objectsCheckedListBox.Items[i]).IndexOf(';') - 4));

                opR = DS.outpost.object_person.FirstOrDefault((op) =>
                {
                    if (op.RowState == DataRowState.Deleted)
                    {
                        return false;
                    }
                    if (op.obj_seq == obj_seq && op.person_seq == changePersonR.person_seq)
                    {
                        return true;
                    }
                    return false;
                });

                if (opR != null)
                {
                    switch (objectsCheckedListBox.GetItemChecked(i))
                    {
                        case true:
                            break;
                        case false:
                            opR.Delete();
                            break;
                        default:
                            break;
                    }
                }
                else//opR == null
                {
                    switch (objectsCheckedListBox.GetItemChecked(i))
                    {
                        case true:
                            DS.outpost.object_person.Addobject_personRow(++op_seq, DS.outpost.person.FindByperson_seq(changePersonR.person_seq), DS.outpost._object.FindByobj_seq(obj_seq));
                            break;
                        case false:
                            break;
                        default:
                            break;
                    }
                }
            }

            try
            {
                DS.personAdapter.Update(DS.outpost.person);
                DS.object_personAdapter.Update(DS.outpost.object_person);
            }
            catch (Exception xException)
            {
                MessageBox.Show(xException.Message);
            }
            Close();
        }

        private void cancelBtn_Click(object sender, EventArgs e)
        {
            Close();
        }


    }
}
